from aaa import models

def all_categories(cate_type):
    first_dict = {}
    x = models.Categories.objects.values('cat_id', 'cat_name', 'cat_pid', 'cat_level', 'cat_deleted').distinct()
    for item in x:
        cat_id = item['cat_id']
        level = item['cat_level']
        cat_pid = item['cat_pid']
        if not cat_pid:
            #一级分类
            first_dict[cat_id] = item
        else:
            #二级分类
            if level == 1:
                if first_dict[cat_pid].get('children',None):
                    first_dict[cat_pid]['children'].append(item)
                else:
                    first_dict[cat_pid]['children'] = [item]
            else:
                #前端添加分类时，级联菜单只需要一级二级分类
                if cate_type != 2:
                    #三级分类
                    for row in first_dict:
                        for i in first_dict[row]['children']:
                            if cat_pid == i['cat_id']:
                                if i.get('children',None):
                                    i['children'].append(item)
                                else:
                                    i['children'] = [item]
    return first_dict